X

Js

How to Check for Changes on a Checkbox

December 29, 2022

/*

Html Checkboxes still Suck



*/

Back when I first got into web development & the only things I was good at was html/css. Checkboxes were a pain to do deal with. You couldn't change the color, the types of checkmarks or the dimensions of the checkbox. Not much has changed, you can change the height & width, but that's about it. You still need to do a duplicate checkbox with another element or use :after/:before in css. We're going to make a simple checkbox with a label for it.

Html for the checkbox

/*

The Change Event


*/

The change event fires when a checkbox gets checked or unchecked. We're going to add an event listener to our checkbox. When it gets checked we're going to display an alert saying "The checkbox has been checked or unchecked".

Adding the change event listener

/*

The Checkbox Checked Property


*/

Now, instead of having the alert we're going to check & see if the checkbox has a check or not. We can do that by checking the checked property of a checkbox. The checked property sets or returns the checked state of a checkbox. We're going to replace the alert with an if statement & evaluate the checked property on a checkbox.

Using the checked property to evaluate the checkbox

Most of these things, if not all are the same for radio buttons. The only difference is a group of radio buttons can only have one selected at a time.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.